import EventEmitter from "events";
import { debounce } from "lodash";
export class RenderView extends EventEmitter {
  textModel_;
  selectionModel_;
  viewContainer_;
  constructor() {
    super();
    this.addEventListener();
  }
  addEventListener() {
    this.textModel_.on("text-change", this.render.bind(this));
    const debounceDomSelectionChangeHandler = debounce(
      this.domSelectionChangeHandler.bind(this),
      50
    );
    window.document.addEventListener(
      "selectionchange",
      debounceDomSelectionChangeHandler
    );
  }
  updateDomSelection() {
    const domSelection = window.getSelection();
    if (domSelection) {
      const selectionFromModel = this.selectionModel_.getSelection();
      const anchor = selectionFromModel.anchor;
      const range = window.document.createRange();
      range.setStart(this.viewContainer_.childNodes[0], anchor);
      range.setEnd(this.viewContainer_.childNodes[0], anchor);
      domSelection.removeAllRanges();
      domSelection.addRange(range);
    }
  }
  domSelectionChangeHandler() {
    const domSelection = window.getSelection();
    if (domSelection) {
      this.emit("selection-change", {
        anchor: domSelection.anchorOffset,
        focus: domSelection.focusOffset,
      });
    }
  }
  render() {
    Promise.resolve().then(() => {
      this.viewContainer_.innerHTML = this.textModel_.getSpacers() + "\n";
      this.updateDomSelection();
    });
  }
}

export default RenderView;
